from PIL import Image
import os
import shutil
from traceback import format_exc

from app.utils.index import file2base64, base2file, PIL2base64
from app.model.request_model import Photo
from app.service.photo_service import PhotoService


def orientation(image: Image) -> Image:
  try:
    exif = image._getexif()
  except AttributeError:
    exif = None

  if exif:
    orientation = exif.get(0x0112)
    print("exif", exif)
    print("orientation", orientation)
    if orientation == 2:
      image = image.transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 3:
      image = image.transpose(Image.ROTATE_180)
    elif orientation == 4:
      image = image.transpose(Image.FLIP_TOP_BOTTOM)
    elif orientation == 5:
     image = image.transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 6:
     image = image.transpose(Image.ROTATE_270)
    elif orientation == 7:
     image = image.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 8:
      image = image.transpose(Image.ROTATE_90)
  return image

def resize_image(input_image_path, size):
  with Image.open(input_image_path) as image:
    # 获取图片的原始宽度和高度
    image = orientation(image)
    return image
    # width, height = image.size
    # print(image.width)
    # print(image.height)
    #
    # # 计算新的宽度和高度
    # new_width = size if width > height else int((size / height) * width)
    # new_height = size if height > width else int((size / width) * height)
    #
    # # 等比例缩放图片
    # resized_image = image.resize((new_width, new_height))
    # return resized_image

def compress_image(input_image_path, output_image_path, quality=75):
  with Image.open(input_image_path) as image:
    image.save(output_image_path, optimize=True, quality=quality)



def make_standardized(file_path, save_dir, save_dir2):
  print("开始处理" + file_path)

  file_name = os.path.basename(file_path)
  base_name, file_ext = os.path.splitext(file_name)

  source_image = resize_image(file_path, 1080)
  source_file = os.path.join(save_dir, file_name)
  stand_file = os.path.join(save_dir, f"{base_name}_标准化{file_ext}")
  stand_life_size_file = os.path.join(save_dir, f"{base_name}_标准化_未裁剪{file_ext}")
  stand_file2 = os.path.join(save_dir2, f"{base_name}{file_ext}")
  stand_life2_size_file = os.path.join(save_dir2, f"{base_name}_标准化_未裁剪{file_ext}")
  mark_file = os.path.join(save_dir, f"{base_name}_标注{file_ext}")
  error_file = os.path.join(save_dir, f"{base_name}_错误.txt")

  try:
    # 拷贝原图
    source_image.save(source_file)
    # shutil.copy(file_path, source_file)

    photo_param = Photo(base64=PIL2base64(source_image))
    photo_service = PhotoService(photo=photo_param)
    # 先保存中间图
    mark = photo_service.photo_mark()
    base2file(mark_file, mark)
    # 标准化裁剪
    resize_img, life_img = photo_service.photo_standardized()
    if not resize_img:
      raise Exception("resize_img is empty")
    if not life_img:
      raise Exception("life_img is empty")
    base2file(stand_file, resize_img)
    base2file(stand_life_size_file, life_img)
    base2file(stand_file2, resize_img)
    base2file(stand_life2_size_file, life_img)

  except Exception as exc:
    with open(error_file, "w") as file:
      file.write(format_exc())


if __name__=="__main__":
  # source_dir = r"E:\workspace\machine-learning\yolo\测试\小程序原图-500"
  source_dir = r"E:\workspace\machine-learning\yolo\测试\长安大学-原始照片"

  save_dir = source_dir + "_结果"
  save_dir2 = source_dir + "_标准化"
  if not os.path.exists(save_dir):
    os.mkdir(save_dir)
  if not os.path.exists(save_dir2):
    os.mkdir(save_dir2)

  for root, dirs, files in os.walk(source_dir):
    index = 1
    total = len(files)
    for file in files:
      print("--", index, "/", total, "--")
      file_path = os.path.join(root, file)
      make_standardized(file_path, save_dir, save_dir2)
      index += 1

  print("全部处理完毕")
